<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal"
    @on-ok="okModal"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="model" :rules="rules" style="padding-top: 20px">
        <n-form-item path="videoType" label="章节类型">
          <n-radio-group
            v-model:value="model.videoType"
            name="left-size"
            style="margin-bottom: 12px"
            :disabled="true"
          >
            <n-radio-button :value="0"> 录播 </n-radio-button>
            <n-radio-button :value="1"> 直播 </n-radio-button>
          </n-radio-group>
        </n-form-item>
        <n-form-item path="videoUrl" label="视频上传">
          <n-upload
            :action="`${apiUrl}/system/oss/upload`"
            :headers="uploadHeaders"
            name="file"
            directory-dnd
            :max="1"
            :show-remove-button="true"
            :default-file-list="uploadList"
            :on-before-upload="handleBeforeUpload"
            :on-finish="handleUploadFinish"
            :on-remove="handleUploadRemove"
          >
            <n-upload-dragger>
              <div style="margin-bottom: 12px">
                <n-icon size="48" :depth="3">
                  <ArchiveIcon />
                </n-icon>
              </div>
              <n-text style="font-size: 16px"> 点击或者拖动文件到该区域来上传 </n-text>
              <n-p depth="3" style="margin: 8px 0 0 0"> 请不要上传敏感数据 </n-p>
            </n-upload-dragger>
          </n-upload>
        </n-form-item>
        <n-form-item path="title" label="章节名称">
          <n-input v-model:value="model.title" />
        </n-form-item>
        <n-form-item path="status" label="是否上架">
          <n-select
            v-model:value="model.isPublish"
            label-field="dictLabel"
            value-field="dictValue"
            :options="statusOptions"
          />
        </n-form-item>
      </n-form>
    </template>
  </basicModal>
</template>
<script setup lang="ts">
  import { basicModal, useModal } from '@/components/Modal';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStore } from '@/store/modules/user';
  import { defineEmits, reactive, ref, watch } from 'vue';
  import { FormRules, useMessage } from 'naive-ui';
  import { saveChapterApi, updateChapterApi } from '@/api/course';
  import { getDictApi } from '@/api/common';
  import { ArchiveOutline as ArchiveIcon } from '@vicons/ionicons5';
  import type { UploadFileInfo } from 'naive-ui';

  const props = defineProps({
    courseInfo: {
      type: Object,
      default: () => null,
    },
    currentRow: {
      type: Object,
      default: () => null,
    },
  });

  const emit = defineEmits(['finish']);

  const { apiUrl } = useGlobSetting();
  const userStore = useUserStore();
  const token = userStore.getToken;

  const model = ref<any>({
    courseId: null,
    chapterId: null,
    videoType: 0,
    title: null,
    videoUrl: null,
    isPublish: 0,
    duration: '00:00', // 视频时长（时分秒格式）
  });

  const rules: FormRules = {
    title: [
      {
        required: true,
        message: '请输入课程名称',
      },
    ],
    isPublish: [
      {
        required: true,
        message: '请选择是否上架',
      },
    ],
    videoUrl: [
      {
        required: true,
        message: '请上传视频',
      },
    ],
  };

  const statusOptions = ref<any[]>([]);

  const uploadList = ref<any[]>([]);
  const uploadHeaders = reactive({
    Authorization: token,
  });

  const handleBeforeUpload = (options: { file: UploadFileInfo; fileList: UploadFileInfo[] }) => {
    const { file } = options;
    if (file.type !== 'video/mp4') {
      message.error('请上传mp4格式的视频');
      return false;
    }
  };

  const handleUploadFinish = ({ file, event }: { file: UploadFileInfo; event?: ProgressEvent }) => {
    const response = (event?.target as XMLHttpRequest).response
      ? JSON.parse((event?.target as XMLHttpRequest).response)
      : {};
    const ext = file.name.split('.')[1];
    file.name = `章节视频.${ext}`;
    if (response?.data) {
      file.url = response.data;
      model.value.videoUrl = response.data;

      // 获取视频时长
      getVideoDuration(response.data);
    }
    return file;
  };

  const handleUploadRemove = () => {
    model.value['videoUrl'] = '';
    model.value['duration'] = '00:00'; // 清除时长
  };

  // 获取视频时长
  const getVideoDuration = (videoUrl: string) => {
    const video = document.createElement('video');
    video.preload = 'metadata';

    video.onloadedmetadata = () => {
      const totalSeconds = Math.floor(video.duration);
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;

      // 格式化时长显示
      let durationText = '';
      if (hours > 0) {
        // 高于一小时显示时分秒
        durationText = `${hours.toString().padStart(2, '0')}:${minutes
          .toString()
          .padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      } else {
        // 低于一小时显示分秒
        durationText = `${minutes.toString().padStart(2, '0')}:${seconds
          .toString()
          .padStart(2, '0')}`;
      }

      model.value.duration = durationText;
      console.log(`视频时长: ${durationText}`);
    };

    video.onerror = () => {
      console.warn('获取视频时长失败');
      model.value.duration = '00:00';
    };

    video.src = videoUrl;
  };

  const formRef = ref();
  const modalRef: any = ref(null);
  const message = useMessage();

  const [modalRegister, { openModal, closeModal, setSubLoading }] = useModal({
    title: '章节',
  });

  async function okModal() {
    formRef.value?.validate(async (errors: any) => {
      if (!errors) {
        try {
          if (model.value?.chapterId) {
            await updateChapterApi(model.value);
            message.success('修改成功');
          } else {
            await saveChapterApi(model.value);
            message.success('新增成功');
          }
          message.destroyAll();
          emit('finish');
        } finally {
          setSubLoading(false);
          closeModal();
        }
      } else {
        console.log(errors);
        setSubLoading(false);
      }
    });
  }

  async function getStatusOptionsDict() {
    const data: any = await getDictApi('yes_or_no');
    statusOptions.value = data || [];
  }

  getStatusOptionsDict();

  function handleClose() {
    model.value = {
      videoType: 0,
      isPublish: 0,
      courseId: props.courseInfo.courseId,
      duration: '00:00',
    };
    uploadList.value = [];
  }

  watch(
    () => props.currentRow,
    (currentRow) => {
      if (!currentRow) {
        model.value = {
          videoType: 0,
          isPublish: 0,
          courseId: props.courseInfo.courseId,
          duration: '00:00',
        };
        uploadList.value = [];
        return;
      }
      model.value = JSON.parse(JSON.stringify(currentRow));
      uploadList.value = model.value.videoUrl
        ? [{ url: model.value.videoUrl, name: '章节视频', status: 'finished' }]
        : [];
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    openModal,
  });
</script>

<style scoped lang="less"></style>
